<template>
  <!-- 打印预览按钮 -->
  <view class="preview-btn-wrapper">
    <button class="preview-btn" @click="openPreview">
      打印预览
    </button>
  </view>

  <!-- 打印预览弹窗 -->
  <view v-if="showPreview" class="preview-modal" @click="closePreview">
    <view class="preview-dialog" @click.stop>
      <view class="preview-header">
        <text class="preview-title">
          打印预览
        </text>
        <text class="close-btn" @click="closePreview">
          ✕
        </text>
      </view>
      <scroll-view class="preview-body" scroll-y>
        <view v-if="templateType === 1" class="preview-content">
          <div v-html="generatePrintContent1()" />
        </view>
        <view v-if="templateType === 2" class="preview-content">
          <div v-html="generatePrintContent2()" />
        </view>
        <view v-if="templateType === 3" class="preview-content">
          <div v-html="generatePrintContent3()" />
        </view>
        <view v-if="templateType === 4" class="preview-content">
          <div v-html="generatePrintContent4()" />
        </view>
      </scroll-view>
      <view class="preview-footer">
        <button class="test-print-btn" @click="handleTestPrint">
          测试打印
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { PrintApi } from '@/api';

// Props
const props = defineProps({
  templateType: {
    type: Number,
    default: 1,
  },
});

// Internal state for print details
const printDetails = ref({
  sellerInfo: '',
  piao_num: '009',
  transactionCenter: '',
  storeReceipt: '',
  maijia: '临时打单',
  sheqian: 100,
  creditDate: '2024-12-20 15:20',
  add_time: '2024-12-20 15:20',
  orderStatus: '已付款',
  total_price: '88',
  notes: '备注信息',
  user: { name: '系统操作员' },
  order_detail: [
    {
      name: '海南大香蕉',
      huozhupici: '(张三-999)',
      add_time: '2024-12-20 15:20',
      goods_price: 88,
      weight: '1',
      unit: '公斤',
      num: '1',
      price: '1',
      order_detail_fujiafei: '测试',
      order_detail_pici: {
        huozhu_name: '张三',
        huozhu: { name: '张三' },
        pici: '11',
      },
    },
  ],
  summary: {
    totalQuantity: 2,
    totalAmount: 88,
    amountOwed: 88,
  },
  qrCodeImage: '',
  staffInfo: {
    operator: '',
    cashier: '',
    salesManager: '',
  },
  disclaimer: '以上食用农产品均履行进货检查法定程序索证索票齐全销售者特此声明。',
});

// Internal state for user info
const userinfo = ref({} as any);

// State
const showPreview = ref(false);

// Methods
const openPreview = () => {
  showPreview.value = true;
};

const closePreview = () => {
  showPreview.value = false;
};

const handleTestPrint = () => {
  try {
    const printer_info = JSON.parse(uni.getStorageSync('printer_info') || '{}');
    if (String(printer_info.printer_type) === '0') {
      if (!checkPrinterConnected()) {
        return;
      }

      uni.showLoading({
        title: '正在打印中…',
        mask: true,
      });

      // 3秒后强制关闭
      setTimeout(() => uni.hideLoading(), 3000);

      // 打印逻辑
      const tpl = props.templateType;
      let work;

      if (tpl === 1) {
        for (let i = 0; i < Number(printer_info.printer_number || 1); i++) {
          setTimeout(() => sprt_printer_template(), 1000);
        }
        work = Promise.resolve();
      }
      else if (tpl === 2) {
        for (let i = 0; i < Number(printer_info.printer_number || 1); i++) {
          setTimeout(() => sprt_printer_template2(), 1000);
        }
        work = Promise.resolve();
      }
      else if (tpl === 3 || tpl === 4) {
        work = handleHtmlPrinting(tpl);
      }
      else {
        work = Promise.resolve();
      }

      work
        .then(() => {
          uni.showToast({
            title: '打印成功',
            icon: 'success',
          });
        })
        .catch((e: any) => {
          uni.showToast({
            title: `打印异常，请重试: ${e?.message || ''}`,
            icon: 'none',
          });
        });
    }
    else {
      const params = { order_id: 123 };
      PrintApi.orderTestPrint(params)
        .then((res) => {
          if (res && res.code === 200) {
            uni.showToast({
              title: res.msg || '打印成功',
              icon: 'success',
            });
          }
          else {
            uni.showToast({
              title: (res && res.msg) || '打印失败',
              icon: 'none',
            });
          }
        })
        .catch((err) => {
          console.error('飞蛾打印异常:', err);
          uni.showToast({
            title: err.msg,
            icon: 'none',
          });
        });
    }
  }
  catch (error: any) {
    console.error('打印函数异常:', error);
    uni.showToast({
      title: `打印异常: ${error?.message || ''}`,
      icon: 'none',
    });
  }
};

const handleHtmlPrinting = async (templateType: number) => {
  const printer_info = JSON.parse(uni.getStorageSync('printer_info') || '{}');

  try {
    // await makebase64QRCode(payQrCodeData, printDetails);

    let previewContent = '';
    if (templateType === 3) {
      previewContent = generatePrintContent3();
    }
    else if (templateType === 4) {
      previewContent = generatePrintContent4();
    }

    for (let i = 0; i < printer_info.printer_number; i++) {
      await printSingleCopy(templateType, previewContent);
      if (i < printer_info.printer_number - 1) {
        await new Promise(resolve => setTimeout(resolve, 1000));
      }
    }
  }
  catch (error: any) {
    console.error('打印失败：', error);
    uni.showToast({
      title: `错误：${error?.message || ''}`,
      icon: 'none',
    });
  }
};

const checkPrinterConnected = () => {
  // 检查打印机连接状态
  if (typeof window.Android !== 'undefined') {
    try {
      const isConnected = window.Android.dIsDeviceConnected();
      if (!isConnected) {
        uni.showToast({
          title: '打印机未连接',
          icon: 'none',
        });
        return false;
      }
      return true;
    }
    catch (e) {
      console.error('检查打印机连接失败:', e);
      return false;
    }
  }
  console.warn('不在 Android 环境中');
  // 非 Android 环境也返回 true 以便测试
  return true;
};

const sprt_printer_template = () => {
  // 模板1打印
  const content = generatePrintContent1();
  if (typeof window.Android !== 'undefined') {
    (window.Android as any).dPrintHtml(content);
  }
};

const sprt_printer_template2 = () => {
  // 模板2打印
  const content = generatePrintContent2();
  if (typeof window.Android !== 'undefined') {
    (window.Android as any).dPrintHtml(content);
  }
};

const printSingleCopy = (templateType: number, content: string) => {
  return new Promise((resolve) => {
    if (typeof window.Android !== 'undefined') {
      (window.Android as any).dPrintHtml(content);
    }
    setTimeout(resolve, 500);
  });
};

// 字段显示检查函数
const isFieldChecked = (groupKey: string, fieldName: string): boolean => {
  try {
    const printerInfo = uni.getStorageSync('printer_info');
    if (!printerInfo) return true;
    const info = JSON.parse(printerInfo);
    if (!info.field || !info.field[groupKey]) return true;

    const groupList = info.field[groupKey];
    const field = groupList.find((item: any) => item.field_name === fieldName);
    return field ? field.checked : true;
  }
  catch (e) {
    console.error('isFieldChecked error:', e);
    return true;
  }
};

// 时间转换函数
const transTime = (timestamp: number): string => {
  const date = new Date(Number(timestamp));
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hour = date.getHours().toString().padStart(2, '0');
  const minute = date.getMinutes().toString().padStart(2, '0');
  const second = date.getSeconds().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};

// 生成打印内容的方法 - 文本样式
const generatePrintContent1 = () => {
  const details = printDetails.value;
  const user = userinfo.value || {} as any;

  let html = `
    <div style="
      width: 80mm;
      padding: 10px 0px 0px 10px;
      box-sizing: border-box;
      font-size: 16px;
      line-height: 1.5;
      color: #000;
      background-color: #fff;
      margin: 0px 0px;
    ">
  `;

  // 标题行 - 操作员和票号
  html += `<div style="text-align: right; margin-bottom: 4px; font-weight: bold; margin-bottom: 20px; font-size: 20px;">`;
  if (isFieldChecked('header', 'cashier_id')) {
    html += `${details.user.name || '系统操作员A'} `;
  }
  if (isFieldChecked('header', 'piao_num')) {
    html += `${details.piao_num || '009'}`;
  }
  html += `</div>`;

  // 交易中心
  if (isFieldChecked('header', 'deal_address')) {
    html += `
      <div style="text-align: center; font-size: 14px;">
        ${user.area || '交易中心'}
      </div>
    `;
  }

  // 销售凭证
  if (isFieldChecked('header', 'voucher')) {
    html += `
      <div style="text-align: center; font-weight: bold; font-size: 20px; margin-bottom: 4px;">
        ${user.dangkou_name || '档口'}-销售凭证
      </div>
    `;
  }

  // 买家
  if (isFieldChecked('header', 'maijia')) {
    html += `
      <div style="margin-bottom: 2px; font-weight: bold; font-size: 20px;">
        买家:${details.maijia || '临时买家'}
      </div>
    `;
  }

  // 分隔线
  html += `<div style="border-top: 1px dashed #000; margin: 10px -10px;"></div>`;

  // 表头
  html += `
    <div style="display: flex; justify-content: space-between; font-weight: bold; margin-bottom: 5px;">
      <div style="width: 30%;">品名</div>
      <div style="width: 23%;">数量</div>
      <div style="width: 23%;">单价</div>
      <div style="width: 23%;">货款</div>
    </div>
  `;

  html += `<div style="border-top: 1px dashed #000; margin: 5px -10px;"></div>`;

  // 商品列表
  details.order_detail.forEach((product: any, index: number) => {
    html += `<div style="display: flex; justify-content: space-between; margin-bottom: 10px; font-weight: bold;">`;

    if (isFieldChecked('goods', 'goods_name')) {
      html += `<div style="width: 30%;">${index + 1}.${product.name || '海南大香蕉'}</div>`;
    }
    else {
      html += `<div style="width: 30%;">--</div>`;
    }

    if (isFieldChecked('goods', 'goods_shuliang')) {
      html += `<div style="width: 23%;">${product.weight || product.num || '1'}${product.unit || '公斤'}</div>`;
    }
    else {
      html += `<div style="width: 23%;">--</div>`;
    }

    if (isFieldChecked('goods', 'goods_danjia')) {
      html += `<div style="width: 23%;">${product.price || '8'}</div>`;
    }
    else {
      html += `<div style="width: 23%;">--</div>`;
    }

    if (isFieldChecked('goods', 'goods_jiage')) {
      html += `<div style="width: 23%;">${product.goods_price || '88'}</div>`;
    }
    else {
      html += `<div style="width: 23%;">--</div>`;
    }

    html += `</div>`;

    // 货主批次
    if (isFieldChecked('goods', 'huozhupici') && product.order_detail_pici) {
      html += `
        <div style="font-size: 12px; margin-bottom: 5px;">
          ${product.order_detail_pici.huozhu_name || '张三'}--${product.order_detail_pici.pici || '9999'}
        </div>
      `;
    }

    // 小计
    if (isFieldChecked('goods', 'goods_total')) {
      html += `
        <div style="text-align: right; font-weight: bold; margin-bottom: 10px;">
          小计:${product.goods_price || '88'}元
        </div>
      `;
    }
  });

  html += `<div style="border-top: 1px dashed #000; margin: 10px -10px;"></div>`;

  // 总计
  if (isFieldChecked('settle', 'zongjine')) {
    html += `
      <div style="font-weight: bold; font-size: 18px; margin-top: 5px;">总计:${details.total_price || '88'}元</div>
    `;
  }

  // 备注
  if (isFieldChecked('settle', 'notes') && details.notes) {
    html += `
      <div style="margin-top: 5px;">备注:${details.notes}</div>
    `;
  }

  // 赊欠信息
  if (isFieldChecked('settle', 'sheqian') && details.sheqian > 0) {
    const currentTime = transTime(new Date().getTime());
    html += `
      <div style="margin-top: 5px;">截止到${currentTime}</div>
      <div style="font-weight: bold; font-size: 18px; margin-top: 5px;">赊欠总额:${details.sheqian}元</div>
    `;
  }

  // 开单时间
  if (isFieldChecked('settle', 'add_time')) {
    html += `
      <div style="margin-top: 5px;">开单时间:${details.creditDate || details.add_time || '2024-12-20 15:20'}</div>
    `;
  }

  // 打印时间
  if (isFieldChecked('settle', 'print_time')) {
    const printTime = transTime(new Date().getTime());
    html += `
      <div style="margin-top: 5px;">打印时间:${printTime}</div>
    `;
  }

  // 档口电话
  if (isFieldChecked('other', 'mobile') && user.dangkou_phone) {
    html += `
      <div style="margin-top: 5px;">档口电话:${user.dangkou_phone}</div>
    `;
  }

  // 档口地址
  if (isFieldChecked('other', 'address') && user.dangkou_address) {
    html += `
      <div style="margin-top: 5px;">档口地址:${user.dangkou_address}</div>
    `;
  }

  // 二维码
  if (isFieldChecked('other', 'pay_qr_code') && details.qrCodeImage) {
    html += `
      <div style="text-align: center; margin: 15px 0;">
        <img src="${details.qrCodeImage}" alt="支付二维码" style="width: 150px; height: 150px;" />
        <div style="margin-top: 5px;">扫描二维码向${user.dangkou_name || '档口'}付款</div>
      </div>
    `;
  }

  // 免责声明
  html += `
    <div style="margin-top: 10px;">${details.disclaimer}</div>
  `;

  html += `</div>`;
  return html;
};

// 生成打印内容的方法 - 多行文本样式
const generatePrintContent2 = () => {
  const details = printDetails.value;
  const user = userinfo.value || {} as any;

  let html = `
    <div style="
      width: 80mm;
      padding: 10px 0px 0px 10px;
      box-sizing: border-box;
      font-size: 16px;
      line-height: 1.5;
      color: #000;
      background-color: #fff;
      margin: 0px 0px;
    ">
  `;

  // 标题行
  if (isFieldChecked('header', 'order_status')) {
    html += `<div style="float: left; font-size: 16px; text-align: left;">${details.orderStatus || '赊欠'}</div>`;
  }

  html += `<div style="float: right; font-size: 16px; text-align: right;">`;
  if (isFieldChecked('header', 'cashier_id')) {
    html += `系统操作员: ${details.user?.name || 'A'}`;
  }
  if (isFieldChecked('header', 'piao_num')) {
    html += ` ${details.piao_num || '009'}`;
  }
  html += `</div>`;
  html += `<div style="clear: both;"></div>`;

  // 交易中心
  if (isFieldChecked('header', 'deal_address')) {
    html += `<div style="text-align: center; font-weight: bold;">${user.area || '交易中心'}</div>`;
  }

  // 销售凭证
  if (isFieldChecked('header', 'voucher')) {
    html += `<div style="text-align: center; font-weight: bold; margin-top:8px;">${user.dangkou_name || '档口'}-销售凭证</div>`;
  }

  // 买家
  if (isFieldChecked('header', 'maijia')) {
    html += `<div style="font-size: 14px; margin-top:8px;">买家: ${details.maijia || '临时打单'}</div>`;
  }

  html += `<div style="text-align:center; margin:8px 0; font-weight:bold; font-size:14px;">---------------订单明细-----------------</div>`;

  // 商品列表
  details.order_detail.forEach((product: any, index: number) => {
    html += `<div style="margin-bottom: 8px; font-size: 14px;">`;
    html += `<div style="display: flex; justify-content: space-between; font-weight: bold;">`;
    html += `<div style="overflow: hidden; text-overflow: ellipsis;">`;

    if (isFieldChecked('goods', 'goods_name')) {
      html += `${index + 1}.${product.name || '品名'}`;
    }
    if (isFieldChecked('goods', 'huozhupici')) {
      html += `${product.huozhupici || product.order_detail_pici?.huozhu_name || ''}`;
    }
    html += `</div>`;

    if (isFieldChecked('goods', 'goods_total')) {
      html += `<div style="text-align: right;">小计:${product.goods_price || 0}元</div>`;
    }
    html += `</div>`;

    // 商品详情（3列布局）
    const detailItems: string[] = [];
    if (isFieldChecked('goods', 'goods_shuliang')) {
      detailItems.push(`数量:${product.num || product.weight || 0}${product.unit || '件'}`);
    }
    if (isFieldChecked('goods', 'goods_danjia')) {
      detailItems.push(`单价:${product.price || 0}`);
    }
    if (isFieldChecked('goods', 'goods_jiage')) {
      detailItems.push(`货款:${product.goods_price || 0}`);
    }

    if (detailItems.length > 0) {
      html += `<table style="width: 100%; border-collapse: collapse; margin: 4px 0;">`;
      const rowCount = Math.ceil(detailItems.length / 3);
      for (let i = 0; i < rowCount; i++) {
        html += `<tr>`;
        for (let j = 0; j < 3; j++) {
          const idx = i * 3 + j;
          const alignment = j === 0 ? 'left' : j === 1 ? 'center' : 'right';
          if (idx < detailItems.length) {
            html += `<td style="width: 33.33%; text-align: ${alignment}; padding: 2px 0;">${detailItems[idx]}</td>`;
          }
          else {
            html += `<td style="width: 33.33%; padding: 2px 0;"></td>`;
          }
        }
        html += `</tr>`;
      }
      html += `</table>`;
    }

    html += `<div style="border-bottom:1px dashed #000; margin: 4px 0;"></div>`;
    html += `</div>`;
  });

  // 总件数
  if (isFieldChecked('goods', 'goods_num')) {
    html += `<div style="font-weight: bold; font-size: 14px;">总件数：${details.summary?.totalQuantity || details.order_detail.length}件</div>`;
  }

  // 结算信息
  html += `<div style="margin-top:4px;">`;
  if (isFieldChecked('settle', 'zongjine')) {
    html += `<div style="font-weight: bold; font-size: 14px; margin-bottom:4px;">总计：${details.total_price || 0}元</div>`;
  }
  if (isFieldChecked('settle', 'sheqian') && details.sheqian > 0) {
    html += `<div style="font-size: 14px; margin-bottom:4px;">截止到${transTime(new Date().getTime())}</div>`;
    html += `<div style="font-weight: bold; font-size: 14px; margin-bottom:4px;">累计赊欠：${details.sheqian}元</div>`;
  }
  html += `</div>`;

  // 其他信息
  if (isFieldChecked('other', 'mobile') && user.dangkou_phone) {
    html += `<div style="margin-bottom:4px; font-size:14px;">联系电话：${user.dangkou_phone}</div>`;
  }
  if (isFieldChecked('other', 'address') && user.dangkou_address) {
    html += `<div style="margin-bottom:4px; font-size:14px;">地址：${user.dangkou_address}</div>`;
  }

  // 二维码
  if (isFieldChecked('other', 'pay_qr_code') && details.qrCodeImage) {
    html += `<div style="text-align:center; margin-bottom:4px;"><img src="${details.qrCodeImage}" style="width: 150px; height: 150px;" alt="二维码" /></div>`;
    html += `<div style="text-align:center; margin-bottom:4px; font-size:14px;">扫描上方二维码向${user.dangkou_name || '档口'}付款</div>`;
  }

  html += `</div>`;
  return html;
};

// 生成打印内容的方法 - 竖向表格样式
const generatePrintContent3 = () => {
  const details = printDetails.value;
  const user = userinfo.value || {} as any;

  let html = `
    <div style="
      width: 80mm;
      padding: 10px 0px 0px 10px;
      box-sizing: border-box;
      font-size: 16px;
      line-height: 1.5;
      color: #000;
      background-color: #fff;
      margin: 0px 0px;
    ">
  `;

  // 标题行
  html += `<div style="text-align: right; margin-bottom: 4px; font-weight: bold; font-size: 20px;">`;
  if (isFieldChecked('header', 'cashier_id')) {
    html += `${details.user.name || '系统操作员'} `;
  }
  if (isFieldChecked('header', 'piao_num')) {
    html += `${details.piao_num || '009'}`;
  }
  html += `</div>`;

  // 交易中心
  if (isFieldChecked('header', 'deal_address')) {
    html += `<div style="text-align: center; font-size: 14px;">${user.area || '交易中心'}</div>`;
  }

  // 销售凭证
  if (isFieldChecked('header', 'voucher')) {
    html += `<div style="text-align: center; font-weight: bold; font-size: 20px; margin-bottom: 4px;">${user.dangkou_name || '档口'}-销售凭证</div>`;
  }

  // 买家
  if (isFieldChecked('header', 'maijia')) {
    html += `<div style="margin-bottom: 2px; font-weight: bold; font-size: 20px;">买家:${details.maijia || '临时打单'}</div>`;
  }

  // 商品列表
  details.order_detail.forEach((product: any, index: number) => {
    html += `<div style="display: flex; justify-content: space-between; margin-bottom: 5px; font-weight: bold;">`;

    if (isFieldChecked('goods', 'goods_name')) {
      html += `<div>${index + 1}.${product.name || '品名'}</div>`;
    }

    if (isFieldChecked('goods', 'goods_total')) {
      html += `<div>小计:${product.goods_price || 0}元</div>`;
    }
    html += `</div>`;

    // 表格
    html += `
      <table border="1" style="width: 100%; border-collapse: collapse; margin-bottom: 5px; border: 0.6px solid black; font-size: 16px;">
        <tr>
    `;

    if (isFieldChecked('goods', 'goods_shuliang')) {
      html += `<th style="border: 0.6px solid black;">件数</th>`;
    }
    html += `<th style="border: 0.6px solid black;">重量</th>`;
    if (isFieldChecked('goods', 'goods_danjia')) {
      html += `<th style="border: 0.6px solid black;">单价</th>`;
    }
    if (isFieldChecked('goods', 'goods_jiage')) {
      html += `<th style="border: 0.6px solid black;">货款</th>`;
    }

    html += `</tr><tr>`;

    if (isFieldChecked('goods', 'goods_shuliang')) {
      html += `<td style="border: 0.6px solid black; text-align: center;">${product.num || 1}</td>`;
    }
    html += `<td style="border: 0.6px solid black; text-align: center;">${product.weight || 1}${product.unit || '公斤'}</td>`;
    if (isFieldChecked('goods', 'goods_danjia')) {
      html += `<td style="border: 0.6px solid black; text-align: center;">${product.price || 0}元/${product.unit || '公斤'}</td>`;
    }
    if (isFieldChecked('goods', 'goods_jiage')) {
      html += `<td style="border: 0.6px solid black; text-align: center;">${product.goods_price || 0}元</td>`;
    }

    html += `</tr></table>`;

    // 货主批次
    if (isFieldChecked('goods', 'huozhupici') && product.order_detail_pici) {
      html += `<div style="font-size: 14px; margin-bottom: 5px;">货主: ${product.order_detail_pici.huozhu_name || ''} 批次: ${product.order_detail_pici.pici || ''}</div>`;
    }
  });

  // 总件数
  if (isFieldChecked('goods', 'goods_num')) {
    html += `<div style="font-weight: bold; font-size: 18px;">总件数:${details.summary?.totalQuantity || details.order_detail.length}件</div>`;
  }

  // 总计
  if (isFieldChecked('settle', 'zongjine')) {
    html += `<div style="font-weight: bold; font-size: 18px;">总计:${details.total_price || 0}元</div>`;
  }

  // 备注
  if (isFieldChecked('settle', 'notes') && details.notes) {
    html += `<div style="margin-top: 5px;">备注:${details.notes}</div>`;
  }

  // 免责声明
  html += `<div style="margin-top: 10px;">${details.disclaimer}</div>`;
  html += `</div>`;
  return html;
};

// 生成打印内容的方法 - 横向表格样式
const generatePrintContent4 = () => {
  const details = printDetails.value;
  const user = userinfo.value || {} as any;

  let html = `
    <div style="
      position: relative;
      width: 100%;
      height: 680px;
      overflow: visible;
    ">
      <div style="
        position: absolute;
        left: 50%;
        top: 50%;
        width: 170mm;
        height: 80mm;
        padding: 5px;
        box-sizing: border-box;
        line-height: 1.1;
        transform: translate(-50%, -50%) rotate(90deg);
        transform-origin: center center;
        color: #000;
        background-color: #fff;
      ">
  `;

  // 标题行
  html += `<div style="display: flex; justify-content: space-between; margin-bottom: 0px; font-weight: bold;">`;

  if (isFieldChecked('header', 'order_status')) {
    html += `<div style="font-size: 24px;">${details.orderStatus || '已付款'}</div>`;
  }
  else {
    html += `<div style="font-size: 24px;">已付款</div>`;
  }

  if (isFieldChecked('header', 'deal_address')) {
    html += `<div style="font-size: 16px; font-weight: 200; text-align: center;">${user.area || '交易中心'}</div>`;
  }

  html += `<div style="text-align: right;">`;
  if (isFieldChecked('header', 'cashier_id')) {
    html += `<span style="font-size: 20px;">${details.user.name || '操作员'}</span>`;
  }
  if (isFieldChecked('header', 'piao_num')) {
    html += `<span style="font-size: 20px;">${details.piao_num || '009'}</span>`;
  }
  html += `</div></div>`;

  // 销售凭证
  if (isFieldChecked('header', 'voucher')) {
    html += `<div style="display: flex; justify-content: center; margin-bottom: 5px; font-weight: bold;"><div style="font-size: 24px;">${user.dangkou_name || '档口'}-销售凭证</div></div>`;
  }

  // 买家
  if (isFieldChecked('header', 'maijia')) {
    html += `<div style="display: flex; justify-content: space-between; margin-bottom: 5px; font-weight: bold;"><div style="font-size: 24px;">买家:${details.maijia || '临时打单'}</div></div>`;
  }

  // 表格
  html += `
    <table border="1" style="width: 100%; table-layout: fixed; border-collapse: collapse; margin-bottom: 5px; border: 0.6px solid black; font-size: 16px;">
      <tr>
  `;

  if (isFieldChecked('goods', 'goods_name')) {
    html += `<th style="width: 20%; border: 0.6px solid black;">品名</th>`;
  }
  if (isFieldChecked('goods', 'huozhupici')) {
    html += `<th style="width: 16%; border: 0.6px solid black;">货主</th>`;
  }
  if (isFieldChecked('goods', 'goods_shuliang')) {
    html += `<th style="width: 12%; border: 0.6px solid black;">数量</th>`;
  }
  html += `<th style="width: 12%; border: 0.6px solid black;">重量</th>`;
  if (isFieldChecked('goods', 'goods_danjia')) {
    html += `<th style="width: 14%; border: 0.6px solid black;">单价</th>`;
  }
  if (isFieldChecked('goods', 'goods_jiage')) {
    html += `<th style="width: 16%; border: 0.6px solid black;">货款</th>`;
  }

  html += `</tr>`;

  // 商品列表
  details.order_detail.forEach((product: any, index: number) => {
    html += `<tr>`;

    if (isFieldChecked('goods', 'goods_name')) {
      html += `<th style="border: 0.6px solid black;">${index + 1}.${product.name || '品名'}</th>`;
    }
    if (isFieldChecked('goods', 'huozhupici')) {
      html += `<th style="border: 0.6px solid black;">${product.order_detail_pici?.huozhu_name || '--'}</th>`;
    }
    if (isFieldChecked('goods', 'goods_shuliang')) {
      html += `<th style="border: 0.6px solid black;">${product.num || 1}</th>`;
    }
    html += `<th style="border: 0.6px solid black;">${product.weight || 1}${product.unit || '公斤'}</th>`;
    if (isFieldChecked('goods', 'goods_danjia')) {
      html += `<th style="border: 0.6px solid black;">${product.price || 0}元/${product.unit || '公斤'}</th>`;
    }
    if (isFieldChecked('goods', 'goods_jiage')) {
      html += `<th style="border: 0.6px solid black;">${product.goods_price || 0}元</th>`;
    }

    html += `</tr>`;
  });

  html += `</table>`;

  // 总计信息
  html += `<div style="font-weight: bold; font-size: 18px;">`;
  if (isFieldChecked('goods', 'goods_num')) {
    html += `总件数:${details.summary?.totalQuantity || details.order_detail.length}件 `;
  }
  if (isFieldChecked('settle', 'zongjine')) {
    html += `总计:${details.total_price || 0}元`;
  }
  html += `</div>`;

  // 备注
  if (isFieldChecked('settle', 'notes') && details.notes) {
    html += `<div style="margin-top: 5px; font-size: 12px;">备注:${details.notes}</div>`;
  }

  // 免责声明
  html += `<div style="margin-top: 5px; font-size: 12px;">${details.disclaimer}</div>`;
  html += `</div></div>`;
  return html;
};

// Initialize user info on mount
onMounted(() => {
  try {
    const userInfoStr = uni.getStorageSync('userInfo');
    if (userInfoStr) {
      userinfo.value = JSON.parse(userInfoStr);
      printDetails.value.transactionCenter = userinfo.value?.area || '';
      printDetails.value.storeReceipt = userinfo.value?.dangkou_name || '';
      printDetails.value.sellerInfo = userinfo.value?.name || '';
      printDetails.value.staffInfo.operator = userinfo.value?.name || '';
      printDetails.value.staffInfo.cashier = userinfo.value?.name || '';
      printDetails.value.staffInfo.salesManager = userinfo.value?.name || '';
    }
  }
  catch (e) {
    console.error('初始化用户信息失败:', e);
  }
});
</script>

<style scoped lang="scss">
// 打印预览按钮样式
.preview-btn-wrapper {
  padding: 20rpx 32rpx;
}

.preview-btn {
  width: 100%;
  height: 80rpx;
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 12rpx;
  font-size: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

// 弹窗遮罩
.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

// 弹窗主体
.preview-dialog {
  width: 90%;
  max-width: 800rpx;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.2);
}

.preview-header {
  padding: 24rpx 30rpx;
  border-bottom: 1rpx solid #eee;
  background-color: #f8f8f8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 40rpx;
  color: #666;
  cursor: pointer;
  line-height: 1;
  padding: 0 10rpx;
}

.preview-body {
  flex: 1;
  overflow-y: auto;
  background-color: #fff;
}

.preview-content {
  border: 1px solid #dcdfe6;
  width: 100%;
  padding: 20px;
  overflow: auto;
  box-sizing: border-box;
  min-height: 400rpx;
  background-color: #fff;
  font-size: 12px;
  color: #000;
}

.preview-footer {
  padding: 24rpx 30rpx;
  border-top: 1rpx solid #eee;
  background-color: #fff;
}

.test-print-btn {
  width: 100%;
  height: 80rpx;
  background-color: #4ca75b;
  color: #fff;
  border: none;
  border-radius: 12rpx;
  font-size: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
